package interfaces.impl;

import java.util.Vector;

import operations.Operation;
import interfaces.Publisher;
import interfaces.Subscriber;

public class PublisherImpl extends Thread implements Publisher {
	private Vector<Operation> operations;
	private Vector<String> operationsName;
	private Semaphore semaphore;
	private Vector<Subscriber> subscribers = null;

	/**
	 * constructeur
	 * 
	 * @param suscriber
	 */
	public PublisherImpl() {
		operations = new Vector<Operation>();
		operationsName = new Vector<String>();
		this.subscribers = new Vector<Subscriber>();
		semaphore = new Semaphore();
	}

	public void addSubscriber(Subscriber suscriber) {
		if (!subscribers.contains(suscriber))
			subscribers.add(suscriber);
	}

	@Override
	public void run() {
		Subscriber temp_subscriber = null;
		while (true) {
			if (operations.size() == 0)
				semaphore.stop();
			else {
				int i = 0;
				while (i < subscribers.size()) {
					temp_subscriber = subscribers.get(i);
					if (temp_subscriber.containtListener(operationsName
							.remove(0))) {
						subscribers.get(i).publish(operationsName.remove(0),
								operations.remove(0));
						i = subscribers.size();
					}
					i++;
				}
			}
		}
	}

	synchronized public boolean addData(String operationName,
			Operation operation) {
		semaphore.signal();
		return operations.add(operation) && operationsName.add(operationName);
	}
	
	public int getSubscriberCount(){
		return subscribers.size();
	}
	
	public Subscriber getSubscriber(int i){
		return subscribers.get(i);
	}
	
	public void removeSubscriber(int i){
		subscribers.remove(i);
	}
}
